package reserve

import (
    "time"
	"strconv"
	"dhfshop/controllers/base"
	"dhfshop/models/reserve"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type ReserveOptController struct {
	base.BaseController
}

func (this *ReserveOptController) CfgInit() {
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	if err := reserve.DeleteReserveOptByPartnerId(partnerId); err != nil {
	    //this.ServeError(err.Error())
		//return
	}
	if err := reserve.DeletePeriodSTLsByPartnerId(partnerId); err != nil {
	    //this.ServeError(err.Error())
		//return
	}
	if err := reserve.DeleteTimeslotSTLsByPartnerId(partnerId); err != nil {
	    //this.ServeError(err.Error())
		//return
	}
	if err := reserve.InitDefaultReserveOpt(partnerId); err != nil {
	    this.ServeError(err.Error())
		return
	}
	if err := reserve.InitDefaultPeriodSTLs(partnerId); err != nil {
	    this.ServeError(err.Error())
		return
	}
	if err := reserve.InitDefaultTimeslotSTLs(partnerId); err != nil {
	    this.ServeError(err.Error())
		return
	}
	rsp := struct {
		PartnerId  int64       `json:"partner_id"`
		Created    time.Time `json:"created"`
	}{PartnerId: partnerId, Created: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *ReserveOptController) List() {
	query,_, fields, order_by, offset, limit, err := this.GetQueryPara()
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	query["partner_id"] = strconv.FormatInt(partnerId, 10)
	l, cnt, err := reserve.GetAllReserveOpts(query, fields, order_by, offset, limit)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	r := struct {
		TotalCount   int64               `json:"total_count"`
		ReserveOpt []*reserve.ReserveOpt `json:"reserveopts"`
	}{TotalCount: cnt, ReserveOpt: l}
	this.Data["json"] = r
	this.ServeJSON()
}

func (this *ReserveOptController) Update() {
	var v reserve.ReserveOpt
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.ReserveOptId, "reserve_opt_id")
	valid.Range(v.CanCancelDays, 1, 30,"can_cancel_days")
	valid.Range(v.CanReserveDays, 1, 30,"can_reserve_days")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	updateFields, err := this.GetUpdateFields(v, "", "form", []string{"print_pub_id"})
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if len(updateFields) > 0 {
		err := reserve.UpdateReserveOptById(&v, updateFields...)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	rsp := struct {
		ReserveOptId  int64     `json:"reserve_opt_id"`
		Modified       time.Time `json:"modified"`
	}{ReserveOptId: v.ReserveOptId, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}
